package com.shunda.pay.utils;

import com.shunda.common.exception.ServiceException;
import com.shunda.pay.config.WxPayConfig;
import com.shunda.pay.dto.ReceiverDto;
import com.shunda.pay.dto.WxChatProfitSharingDto;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import com.wechat.pay.java.service.profitsharing.model.CreateOrderReceiver;
import com.wechat.pay.java.service.profitsharing.model.CreateOrderRequest;
import com.wechat.pay.java.service.profitsharing.model.OrdersEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 手动分账工具类
 */
public class WxPayProfitSharingUtil {

    private static final Logger log = LoggerFactory.getLogger(WxPayProfitSharingUtil.class);

    /**
     * 封装微信分账参数
     */
    private static CreateOrderRequest getProfitParams(WxPayConfig wxPayConfig, WxChatProfitSharingDto dto) {
        CreateOrderRequest request = new CreateOrderRequest();
        request.setAppid(wxPayConfig.getAppId());
        request.setTransactionId(dto.getWxOrderId());
        request.setOutOrderNo(dto.getOrderId());
        List<ReceiverDto> receivers = dto.getReceivers();
        List<CreateOrderReceiver> createOrderReceivers = new ArrayList<>();
        for (ReceiverDto receiver : receivers) {
            CreateOrderReceiver orderReceiver = new CreateOrderReceiver();
            orderReceiver.setAccount(receiver.getAccount());
            orderReceiver.setType(receiver.getType());
            orderReceiver.setName(receiver.getName());
            orderReceiver.setAmount(receiver.getAmount());
            orderReceiver.setDescription(receiver.getDescription());
            createOrderReceivers.add(orderReceiver);
        }
        request.setReceivers(createOrderReceivers);
        request.setUnfreezeUnsplit(true);
        return request;
    }

    /**
     * 请求分账
     *
     * @param wxPayConfig 微信配置信息
     * @param param       请求分账请求参数
     * @return 分账账单号
     */
    public static String profitSharing(WxPayConfig wxPayConfig, WxChatProfitSharingDto param,
                                       RSAAutoCertificateConfig rsaAutoCertificateConfig) {
        ProfitsharingService service =
                new ProfitsharingService.Builder()
                        .config(rsaAutoCertificateConfig)
                        .build();
        OrdersEntity response = null;
        try {
            CreateOrderRequest request = getProfitParams(wxPayConfig, param);
            response = service.createOrder(request);
        } catch (HttpException e) { // 发送HTTP请求失败
            log.error("微信请求分账发送HTTP请求失败，错误信息：{}", e.getHttpRequest());
        } catch (ServiceException e) { // 服务返回状态小于200或大于等于300，例如500
            log.error("微信请求分账服务状态错误，错误信息：{}", e.getMessage());
        } catch (MalformedMessageException e) { // 服务返回成功，返回体类型不合法，或者解析返回体失败
            log.error("服务返回成功，返回体类型不合法，或者解析返回体失败，错误信息：{}", e.getMessage());
        }
        if (response != null) {
            log.info("微信请求分账成功，返回值：{}", response);
            // 返回分账账单号返回值
            return response.getOrderId();
        }
        return null;
    }
}
